import { getFRPPage, frpFetch, getProductionOrderList, getOrderId } from "./util.js"
import frpOption from "../option.json" with { type: "json" }
import logger from "./logger.js"

import { getStorageKey, localStorage, StorageKeyType } from "./localStorage.js"

async function puppeteerTaskProcess(orderCode) {
    let browser, page

    try {
        ; ({ browser, page } = await getFRPPage(frpOption.page.taskCenter))
        if (!browser) {
            return
        }

        // 切换到生产任务标签页
        await page.evaluate(() => {
            // eslint-disable-next-line no-undef
            const tabButton = Array.from(document.querySelectorAll(".text_inner")).find((item) => item.innerText === "生产任务")
            tabButton.click()
        })
        await page.waitForNetworkIdle()

        // 筛选对应合同
        const orderFilterInput = await page.evaluateHandle(() => {
            // eslint-disable-next-line no-undef
            const input = Array.from(document.querySelectorAll(".ch4bzxqa3j50000ykwyg"))
                .find((item) => item.innerText === "合同编码")
                .nextElementSibling.querySelector("input")
            return input
        })
        await orderFilterInput.type(orderCode)
        await page.evaluate((input) => {
            input.blur()
        }, orderFilterInput)
        await page.waitForNetworkIdle()

        // 拿到报工按钮
        const startButton = await getButton("开始")
        const reportButton = await getButton("报工")
        const issueButton = await getButton("下发")
        async function getButton(buttonText) {
            return page.evaluateHandle((buttonText) => {
                // eslint-disable-next-line no-undef
                const buttonList = Array.from(document.querySelectorAll("button"))
                return buttonList.find((item) => item.innerText === buttonText)
            }, buttonText)
        }

        // 拿到工段和单据下标
        const { sectionIndex, codeIndex, itemNumIndex } = await page.evaluate(async () => {
            // eslint-disable-next-line no-undef
            const tableHeadContainer = document.querySelector(".cpbtpnta3j5000084nq0")
            const tableHeadList = Array.from(tableHeadContainer.querySelectorAll(".ch4bzxqa3j50000ykwyg"))
            const sectionIndex = tableHeadList.findIndex((item) => item.innerText === "工段")
            const codeIndex = tableHeadList.findIndex((item) => item.innerText === "生产订单编码")
            const itemNumIndex = tableHeadList.findIndex((item) => item.innerText === "总数量 / 进入环节数量")
            return { sectionIndex, codeIndex, itemNumIndex }
        })

        // 后整理报工会更新列表
        let task = await getCurrTask()
        await clickTask(task)
        await page.waitForNetworkIdle()

        async function clickTask(task) {
            await page.evaluate((task) => {
                const activeColor = "rgb(239, 224, 185)"
                if (task.style.backgroundColor !== activeColor) {
                    task.click()
                }
            }, task)
        }

        const successCodeList = []
        while (task != null) {
            const productionCode = await getTaskInfo(task, codeIndex)
            let currSection = await getTaskInfo(task, sectionIndex)
            const itemNum = (await getTaskInfo(task, itemNumIndex)).split("/")[0]
            let { activeButton, buttonText } = await getActiveButton()

            while (currSection !== "后整理" || buttonText !== "报工") {
                activeButton.click()
                await page.waitForNetworkIdle()

                // 裁剪报工特殊操作
                if (currSection === "裁剪" && buttonText === "报工") {
                    const submitButton = await page.evaluateHandle(async () => {
                        // eslint-disable-next-line no-undef
                        const bannerList = Array.from(document.querySelectorAll(".ih5-rel-banner"))
                        // eslint-disable-next-line no-undef
                        const cancelButton = Array.from(document.querySelectorAll("button")).find((item) => item.innerText === "取消")
                        const reportPanel = bannerList.find((item) => item.contains(cancelButton))
                        const checkAll = reportPanel.querySelector(".ih5-rel-checkbox")
                        checkAll.click()
                        return Array.from(reportPanel.querySelectorAll("button")).find((item) => item.innerText === "报工")
                    })
                    await page.waitForNetworkIdle()
                    await page.evaluate(async (submitButton) => {
                        submitButton.click()
                    }, submitButton)
                    await page.waitForNetworkIdle()
                    console.log(currSection + buttonText + "成功")
                }

                // 下发选择件数
                if (buttonText === "下发" || (currSection === "后整理" && buttonText === "报工")) {
                    await typeItemNum(itemNum)
                }

                await clickTask(task)

                currSection = await getTaskInfo(task, sectionIndex)
                    ; ({ activeButton, buttonText } = await getActiveButton())
            }

            // await activeButton.click()
            // await page.waitForNetworkIdle()
            // await typeItemNum(itemNum)
            successCodeList.push(productionCode)

            task = await getCurrTask(successCodeList)
            await clickTask(task)

            async function typeItemNum(number) {
                const issuePanel = await page.evaluateHandle(async () => {
                    // eslint-disable-next-line no-undef
                    const bannerList = Array.from(document.querySelectorAll(".ih5-rel-banner"))
                    // eslint-disable-next-line no-undef
                    const cancelButton = Array.from(document.querySelectorAll("button")).find((item) => item.innerText === "取消")
                    return bannerList.find((item) => item.contains(cancelButton))
                })
                const input = await page.evaluateHandle(async (issuePanel) => {
                    return issuePanel.querySelector("input")
                }, issuePanel)
                await input.type(number)
                await page.evaluate(async (issuePanel) => {
                    const submitButton = Array.from(issuePanel.querySelectorAll("button")).find((item) => item.innerText === "保存")
                    submitButton.click()
                }, issuePanel)
                await page.waitForNetworkIdle()
            }
        }

        console.log(orderCode + "所有工段报工成功")

        async function getCurrTask(successCodeList) {
            return page.evaluateHandle(
                async (successCodeList, codeIndex) => {
                    // eslint-disable-next-line no-undef
                    const tableHeadContainer = document.querySelector(".cpbtpnta3j5000084nq0")
                    const taskList = Array.from(tableHeadContainer.parentElement.nextElementSibling.children)

                    if (!successCodeList) {
                        return taskList[0]
                    }
                    successCodeList = successCodeList || []
                    return taskList.find((item) => !successCodeList.includes(item.children[codeIndex].innerText))
                },
                successCodeList,
                codeIndex
            )
        }

        async function getActiveButton() {
            const activeButton = await page.evaluateHandle(
                async (startButton, reportButton, issueButton) => {
                    const buttonList = [startButton, reportButton, issueButton]
                    const activeColor = "rgb(191, 162, 96)"
                    return buttonList.find((item) => item.style.backgroundColor === activeColor)
                },
                startButton,
                reportButton,
                issueButton
            )
            const buttonText = await getElementText(activeButton)

            return {
                activeButton,
                buttonText,
            }
        }

        async function getElementText(element) {
            return page.evaluate((element) => element.innerText, element)
        }

        async function getTaskInfo(task, fieldIndex) {
            return page.evaluate(
                async (task, fieldIndex) => {
                    return task.children[fieldIndex].innerText
                },
                task,
                fieldIndex
            )
        }
    } finally {
        await browser?.close()
    }
}

async function taskProcess(orderCode, productionOrderList) {
    const storageKey = getStorageKey(orderCode, StorageKeyType.taskProcess)
    let finishProductionCode = JSON.parse(localStorage.getItem(storageKey)) || []

    if (!productionOrderList) {
        const orderId = await getOrderId(orderCode)
        productionOrderList = await getProductionOrderList(orderId)
    }

    const runProductionId = productionOrderList.filter(item => !finishProductionCode.includes(item.code)).map(item => item['数据ID'])

    const getProductionRes = await frpFetch(frpOption.api.getFormList, {
        offset: 0,
        limit: 100,
        formCode: "productionTask",
        filter: `( productionOrderId IN (${runProductionId.join(',')}) ) AND sectionType = '后整理'`,
        action: "查看",
        auth: 73,
    })
    console.log(`( productionOrderId IN (${runProductionId.join(',')}) ) AND sectionType = '后整理'`, getProductionRes)
    if (getProductionRes.code !== 200) {
        throw new Error(`taskProcess获取生产任务失败: ${getProductionRes.reason || JSON.stringify(getProductionRes)}`)
    }
    const taskList = getProductionRes.data || []

    const errMsgList = []
    for (const task of taskList) {
        task.status = 1
        // task.endDate = getDate()
        // task.reportNum = task.totalNum
        const reportRes = await frpFetch(frpOption.api.editProductionTask, {
            session: frpOption.session,
            action: "报工",
            auth: 73,
            num: 0,
            productionTask: task,
        })
        if (reportRes.code !== 200) {
            let reason = reportRes.reason
            if (typeof reason === 'object') {
                reason = JSON.stringify(reason)
            }
            errMsgList.push(`${task.productionOrderCode} 报工失败: ${reason || JSON.stringify(reportRes)}`)
        } else {
            finishProductionCode.push(task.productionOrderCode)
            logger.info(`${task.productionOrderCode} 报工成功`)
        }
    }

    localStorage.setItem(storageKey, JSON.stringify(finishProductionCode))

    if (errMsgList.length > 0) {
        throw new Error('\n' + errMsgList.join("\n"))
    }
}

function getDate() {
    const now = new Date()
    const month = now.getMonth() + 1
    return `${now.getFullYear()}-${month < 10 ? "0" : ""}${month}-${now.getDate()} ${now.toLocaleString().split(" ")[1]}`
}

export { taskProcess, puppeteerTaskProcess }
